@model Nop.Admin.Models.Logistics.PlanningOverviewModel
@using Telerik.Web.Mvc.UI
@using Nop.Core.Domain.Logistics
@using Nop.Core.Domain.Shipping
@using Nop.Admin.Models.Logistics
@{  
    var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;
    //page title
    ViewBag.Title = T("Admin.Logistics.Planning.Overview").Text;
}
<script>
    function onDistrictChange(e)
    {
        var url = '@Html.Raw(Request.Url.AbsolutePath)';
        var selectedDistrictId = $('#SelectedDistrictId').val();
        window.location = url + "?DistrictId=" + selectedDistrictId;
    }
</script>

@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <img src="@Url.Content("~/subsites/Administration/Content/images/ico-delivery.png")" alt="" />
            @T("Admin.Logistics.Planning.Overview").Text  ---   @T("Admin.Logistics.District").Text: @Model.DistrictName
        </div>
        <div class="options">
            <input type="button" id="plan" class="t-button" value="@T("Admin.Logistics.Planning.StartPlan")" />
        </div>
    </div>

    @Html.HiddenFor(model => model.DistrictId);

    <table>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SelectedDistrictId):
            </td>
            <td class="adminData">
                @(Html.Telerik().DropDownListFor(model => model.SelectedDistrictId)
                    .BindTo(Model.AvailableDistricts)
                    .Name(Html.FieldIdFor(model => model.SelectedDistrictId))
                    .ClientEvents(events => events.OnChange("onDistrictChange")))
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.WarehouseId):
            </td>
            <td class="adminData">
                @(Html.Telerik().DropDownListFor(model => model.WarehouseId)
                    .BindTo(Model.AvailableWarehouses)
                    .Name(Html.FieldIdFor(model => model.WarehouseId))
                    .DropDownHtmlAttributes(
                        new
                        {
                            style = "width: 400px;",
                        })
                )
            </td>
        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.SelectedTimeSpans):
            </td>
            <td class="adminData">
                @*@Html.Telerik().ComboBoxFor(model => model.SelectedTimeSpans).BindTo(Model.AvailableTimeSpans).Name(Html.FieldIdFor(model => model.SelectedTimeSpans)))*@
                @*@if (Model.AvailableTimeSpans.Count > 0)
                    {
                        foreach (var timeSpan in Model.AvailableTimeSpans)
                        {
                            <div>
                            <input type="checkbox" name="@Html.NameFor(model => model.SelectedTimeSpans)" value="@timeSpan.Value">
                            <label>@timeSpan.Text</label>
                            </div>
                        }
                    }*@
                @Html.ListBoxFor(model => model.SelectedTimeSpans, Model.AvailableTimeSpans,
                new
                {
                    id = "SelectedTimeSpans",
                    Multiple = "multiple",
                    Size = 6,
                    style = "width: 100%;"
                })
            </td>



        </tr>

        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.LogisticArea):
            </td>
            <td class="adminData">
                @Html.ListBoxFor(model => model.LogisticArea, Model.AvailableLogisticAreas,
                                 new
                                 {
                                     id = "LogisticArea",
                                     Multiple = "multiple",
                                     Size = 10,
                                     style = "width: 100%;"
                                 })
            </td>
        </tr>
        @*TODO: Disable the courier filter, coz the couriers are not assigned by areas yet.*@
        @*<tr>
                <td class="adminTitle">
                    @Html.NopLabelFor(model => model.SearchCourierFilter):
                </td>
                <td class="adminData">
                    @(Html.Telerik().DropDownListFor(model => model.SearchCourierFilter)
                        .Name("SearchCourierFilter")
                        .BindTo(Model.AvailableCouriersFilters)
                        .Placeholder(T("Admin.Logistics.SelectCourierFilter").Text)
                        .CascadeTo("CourierId")
                    )
                </td>
            </tr>*@
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.CourierId):
            </td>
            <td class="adminData">
                @(Html.Telerik().DropDownList()
                    .Name("CourierId")
                    .DataBinding(binding => binding.Ajax().Select("CourierList", "Logistics", new { districtId = Model.DistrictId }))
                    .Placeholder(T("Admin.Logistics.SelectCourier").Text)
                    .DropDownHtmlAttributes(
                        new
                        {
                            style = "width: 400px;",
                        })
                )
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.DisplayNotReady):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.DisplayNotReady)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.InWarehouseOnly):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.InWarehouseOnly)
            </td>
        </tr>
        <tr>
            <td class="adminTitle">
                @Html.NopLabelFor(model => model.IncludeMaxDeliveryAttempt):
            </td>
            <td class="adminData">
                @Html.EditorFor(model => model.IncludeMaxDeliveryAttempt)
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="button" id="refresh-packages" class="t-button" value="@T("Admin.Logistics.RefreshPackages")" />
            </td>
        </tr>
    </table>
    <p>
    </p>

    <table class="adminContent">
        <tr>
            <td>

                @(Html.Telerik().Grid<LogisticsPackageModel>()
                    .Name("pending-packages")
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.Id)
                            .Filterable(false)
                            .Template(x => string.Format("<input type='checkbox' name='checkedPackages' value='{0}' class='checkboxGroups'/>", x.Id))
                            .ClientTemplate("<input type='checkbox' name='checkedPackages' value='<#= Id #>' class='checkboxGroups'/>")
                            .Title("<input id='mastercheckboxPackages' type='checkbox'/>")
                            .Width(50)
                            .Sortable(false)
                            .HtmlAttributes(new { style = "text-align:center" })
                            .HeaderHtmlAttributes(new { style = "text-align:center" });
                        columns.Bound(x => x.Id)
                            .Filterable(false)
                            .Centered()
                            .Template(x => Html.ActionLink(x.Id.ToString(), "PackageEdit", new { id = x.Id }))
                            .ClientTemplate("<a href=\"PackageEdit/<#= Id #>\"><#= Id #></a>");
                        @*.Title(T("Admin.Logistics.Common.Fields.PackageId").Text);*@
                        columns.Bound(x => x.Attribute)
                            .Title(T("Admin.Logistics.Common.Fields.AddOn").Text);
                        columns.Bound(x => x.Reference)
                            .Sortable(false)
                            .HtmlAttributes(new { style = "min-width: 90px; max-width: 90px; word-wrap: break-word" });
                        columns.Bound(x => x.TrackingNumber)
                            .HtmlAttributes(new { style = "min-width: 150px; word-wrap: break-word; word-break: break-all" });
                        columns.Bound(x => x.StatusName)
                            .Title(T("Admin.Logistics.Common.Fields.Status").Text);
                        columns.Bound(x => x.LatestPackageNoteContent)
                            .Title(T("Admin.Logistics.Common.Fields.PackageNote").Text)
                            .Sortable(false)
                            .HtmlAttributes(new { style = "min-width: 90px; max-width: 90px; word-wrap: break-word" });
                        columns.Bound(x => x.PickUpLocation.Address.Company).Title(T("Admin.Logistics.SenderCompanyName").Text);
                        columns.Bound(x => x.PickUpLocation.Address.Type);
                        columns.Bound(x => x.PickupAddressString)
                            .Sortable(false)
                            .Template(x => Html.ActionLink(x.PickupAddressString, "AddressEdit", new { locationId = x.PickUpLocationId }))
                            .ClientTemplate("<a href=\"AddressEdit?locationId=<#= PickUpLocationId #>\"><#= PickupAddressString #></a>")
                            .Title(T("Admin.Logistics.PickupAddress").Text);
                        columns.Bound(x => x.PickUpZone)
                            .Width(60)
                            .Title(T("Admin.Logistics.Common.Fields.PZone").Text);
                        columns.Bound(x => x.DeliveryLocation.Address.Company).Title(T("Admin.Logistics.ReceiverCompanyName").Text);
                        columns.Bound(x => x.DeliveryLocation.Address.Type);
                        columns.Bound(x => x.DeliveryAddressString)
                            .Sortable(false)
                            .Template(x => Html.ActionLink(x.DeliveryAddressString, "AddressEdit", new { locationId = x.DeliveryLocationId }))
                            .ClientTemplate("<a href=\"AddressEdit?locationId=<#= DeliveryLocationId #>\"><#= DeliveryAddressString #></a>")
                            .Title(T("Admin.Logistics.DeliveryAddress").Text);
                        columns.Bound(x => x.DeliveryZone)
                            .Width(60)
                            .Title(T("Admin.Logistics.Common.Fields.DZone").Text);
                        columns.Bound(x => x.DeliveryLocation.DistrictName)
                            .Title(T("Admin.Logistics.District").Text);
                        columns.Bound(x => x.ScheduledTime)
                            .Template(x => x.ScheduledTime).ClientTemplate("<#= ScheduledTime #>");
                        columns.Bound(x => x.CreatedOn).Template(x => x.CreatedOnStr).ClientTemplate("<#= CreatedOnStr #>");
                        columns.Bound(x => x.UpdatedOn).Template(x => x.UpdatedOnStr).ClientTemplate("<#= UpdatedOnStr #>");
                        columns.Bound(x => x.WarehouseAddressString).Title(T("Admin.Logistics.WarehouseAddress").Text)
                            .Sortable(false);
                        columns.Bound(x => x.DeliveryAttemptCount);
                        columns.Bound(x => x.Id)
                            .Filterable(false)
                            .Sortable(false)
                            .Centered()
                            .Template(x => Html.ActionLink(T("Admin.Logistics.PrintPackagingSlip").Text, "PrintPackageWaybillAsPdf", new { id = x.Id }))
                            .ClientTemplate("<a href=\"PrintPackageWaybillAsPdf/<#= Id #>\"><#= Id #></a>")
                            .Title(T("Admin.Logistics.PrintPackagingSlip").Text);
                        columns.Bound(x => x.OrderKindId).Hidden(true);
                    })
            .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
            .DataBinding(dataBinding => dataBinding.Ajax().Select("PendingPackagesOverviewList", "Logistics"))
            .ClientEvents(events => events.OnDataBinding("onDataBinding").OnDataBound("onDataBound"))
            .Reorderable(reorder => reorder.Columns(true))
            .EnableCustomBinding(true))
            </td>

        </tr>
    </table>

    <script type="text/javascript">

    var selectedIds = [];

    $(document).ready(function () {

        //search button
        $('#refresh-packages').click(function () {
            //search
            var grid = $('#pending-packages').data('tGrid');
            grid.currentPage = 1; //new search. Set page size to 1
            grid.ajaxRequest();
            //clear selected checkboxes
            $('.checkboxGroups').attr('checked', false).change();
            selectedIds = [];
            return false;
        });

        $('#plan').click(function (e) {
            e.preventDefault();
            //redirect to required URL
            setLocation('@(Url.Action("Plan", "Logistics"))?selectedIds=' + selectedIds.join(",") + '&selectedtimespan=' + $('#@Html.FieldIdFor(model=>model.SelectedTimeSpans)').val() + '&selectedDistrictId=' + $('#@Html.FieldIdFor(model=>model.SelectedDistrictId)').val() + '&courierId=' + $('#CourierId').val() + '&warehouseId=' + $('#@Html.FieldIdFor(model => model.WarehouseId)').val());
            return false;
        });

        $('#mastercheckboxPackages').click(function () {
            $('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
        });

        //wire up checkboxes.
        $('#pending-packages input[type=checkbox][id!=mastercheckboxPackages]').live('change', function (e) {
            var $check = $(this);
            if ($check.is(":checked") == true) {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked == -1) {
                    //add id to selectedIds.
                    selectedIds.push($check.val());
                }
            }
            else {
                var checked = jQuery.inArray($check.val(), selectedIds);
                if (checked > -1) {
                    //remove id from selectedIds.
                    selectedIds = $.grep(selectedIds, function (item, index) {
                        return item != $check.val();
                    });
                }
            }
            updateMasterCheckbox();
        });
    });

    function onDataBinding(e) {
        var multiLogisticArea = [];
        var x = document.getElementById("LogisticArea");
        for (var i = 0; i < x.options.length; i++) {
            if (x.options[i].selected == true) {
                multiLogisticArea.push(x.options[i].value);
            }
        }

        var LogisticAreaString = multiLogisticArea.join(",");
        var searchModel = {
            //LogisticArea: $('#LogisticArea').val(),
            LogisticArea: LogisticAreaString,
            WarehouseId: $('#@Html.FieldIdFor(model => model.WarehouseId)').val(),
            SelectedDistrictId: $('#@Html.FieldIdFor(model => model.SelectedDistrictId)').val(),
            SelectedTimeSpans: $('#@Html.FieldIdFor(model=>model.SelectedTimeSpans)').val(),            
            CourierId: $('#CourierId').val(),
            DisplayNotReady: $('#@Html.FieldIdFor(model => model.DisplayNotReady)').is(':checked'),
            InWarehouseOnly: $('#@Html.FieldIdFor(model => model.InWarehouseOnly)').is(':checked'),
            IncludeMaxDeliveryAttempt: $('#@Html.FieldIdFor(model => model.IncludeMaxDeliveryAttempt)').is(':checked')
            };
            e.data = searchModel;
        }

        function onDataBound(e) {
            $('#pending-packages input[type=checkbox][id!=mastercheckboxPackages]').each(function () {
                var currentId = $(this).val();
                var checked = jQuery.inArray(currentId, selectedIds);
                //set checked based on if current checkbox's value is in selectedIds.
                $(this).attr('checked', checked > -1);
            });

            updateMasterCheckbox();
            changeColorByOrderKind();
        }

        function updateMasterCheckbox() {
            var numChkBoxes = $('#pending-packages input[type=checkbox][id!=mastercheckboxPackages]').length;
            var numChkBoxesChecked = $('#pending-packages input[type=checkbox][checked][id!=mastercheckboxPackages]').length;
            $('#mastercheckboxPackages').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
        }

        function changeColorByOrderKind() {
            var trObj = $('#pending-packages tbody tr');
            if (trObj.length <= 0) return;
            $.each(trObj, function () {
                var kindId = $(this).find('td:last').text();
                if (kindId == '10') {
                    $(this).css('background-color', '#b6d7a8');
                } else if (kindId == '20') {
                    $(this).css('background-color', '#c9daf8');
                }
            });
        }
    </script>  
}
